package com.example.statistics.ui.sales

import android.os.Bundle
import android.text.method.DigitsKeyListener
import com.example.statistics.R
import com.example.statistics.bean.*
import com.example.statistics.common.BaseActivity
import com.example.statistics.ex.*
import com.example.statistics.net.UrlConfig
import com.example.statistics.net.callback.DataDialogHttpCallback
import com.example.statistics.ui.customer.CustomerListActivity
import com.example.statistics.ui.product.ProductInfoListActivity
import com.example.statistics.utils.Constants
import com.example.statistics.utils.activityFinish
import com.example.statistics.utils.activityForResult
import com.google.gson.Gson
import com.jhj.httplibrary.HttpCall
import com.jhj.httplibrary.utils.ExtraRequestBodyUtils
import com.example.statistics.ex.afterTextChangedListener
import kotlinx.android.synthetic.main.activity_sales_statistics_edit.*
import kotlinx.android.synthetic.main.list_item_add.*
import kotlinx.android.synthetic.main.list_item_sales_statistics.view.*
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.toast
import java.util.*

/**
 * 销售统计
 */

class SalesStatisticsEditActivity : BaseActivity() {

    private var salesProductList = mutableListOf<SalesProduct>()

    override val title: String
        get() = "销售统计"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sales_statistics_edit)
        val id = intent.getIntExtra(Constants.ID, 0)
        var sellerList: List<SellerBean>? = null
        var seller: SellerBean? = null
        var order = SalesOrder()
        httpGet<List<SellerBean>>(UrlConfig.SELLER_LIST, config = {
            isShowDialog = true
        }) {
            sellerList = it
        }
        if (id != 0) {
            httpGet<SalesOrder>(UrlConfig.SALES_STATISTICS_DATA, config = {
                listParams = listOf("id" to id)
            }) {
                order = it ?: SalesOrder()
                tv_customer.contentText = order.customerName
                if (order.sellerId != 0) {
                    seller = sellerList?.find { sellerBean -> sellerBean.id == order.sellerId }
                    tv_seller.contentText = seller?.sellerName.orEmpty()
                }
                order.salesProductList.forEach { bean ->
                    salesProduct(bean)
                }
            }
        } else {
            salesProduct()
        }


        tv_customer.onSymbolClicked { str ->
            activityForResult<CustomerListActivity>(
                    Constants.DATA to (if (str.isNullOrBlank()) Constants.SELECTOR else str)
            ) {
                val customer = it?.getSerializableExtra(Constants.DATA) as Customer?
                tv_customer.contentText = customer?.name
                if (customer?.sellerId != null) {
                    seller = sellerList?.find { sellerBean -> sellerBean.id == customer.sellerId }
                    tv_seller.contentText = seller?.sellerName.orEmpty()
                    order.sellerId = seller?.id.orEmpty()
                }
                order.customerId = customer?.ID.orEmpty()
                order.customerName = customer?.name.orEmpty()
            }
        }
        tv_seller.onContentClicked {
            bottomSingleDialog(list = sellerList?.map { it.sellerName }.orEmpty()) { _, s ->
                tv_seller.contentText = s
                seller = sellerList?.find { it.sellerName == s }
                order.sellerId = seller?.id.orEmpty()
            }
        }
        //val date = Date().format()
        val date = preferenceFind(String::class.java, "statisticsDate") ?: Date().format()
        tv_date.contentText = date
        order.date = date.orEmpty()
        tv_date.onDateClicked {
            order.date = it
        }

        topBarRightText("保存") {
            preferenceSave(tv_date.contentText, "statisticsDate")
            if (order.customerId == 0) {
                toast("请确定顾客")
                return@topBarRightText
            }
            if (seller == null) {
                toast("请确定经历人")
                return@topBarRightText
            }
            salesProductList = salesProductList.filter {
                it.customerId = order.customerId
                it.customerName = order.customerName
                it.date = order.date
                it.productId != 0 && it.salesNumber.orEmpty() > 0 && it.salesPrice.orEmpty() > 0
            }.toMutableList()
            order.totalPrice = salesProductList.sumEx { it.salesTotalPrice ?: 0 }.toDouble()
            order.arrears = order.totalPrice
            order.salesProductList = salesProductList

            val json = Gson().toJson(order)
            val requestBody = ExtraRequestBodyUtils.upJson(json)
            val url = if (id != 0) UrlConfig.SALES_STATISTICS_UPDATE else UrlConfig.SALES_STATISTICS_ADD
            HttpCall.post(url)
                    .upRequestBody(requestBody)
                    .enqueue(object : DataDialogHttpCallback<SalesOrder>(this) {
                        override fun onSuccess(data: SalesOrder?, resultType: ResultType) {
                            toast(data?.date.orEmpty())
                            activityFinish()
                        }
                    })
        }

        layout_add.onClick {
            salesProduct()
        }
    }

    val list = listOf(
            ProductBean(id = 42, factoryNo = "791C", productName = "圆肚", specification = "13.61"),
            ProductBean(id = 201, factoryNo = "13597", productName = "片肚", specification = "13.61"),
            ProductBean(id = 202, factoryNo = "31965", productName = "片肚", specification = "13.61"),
            ProductBean(id = 333, factoryNo = "717", productName = "熟肚", specification = "10"),
            ProductBean(id = 169, factoryNo = "717M", productName = "熟肚", specification = "10"),
            ProductBean(id = 342, factoryNo = "320M", productName = "熟肚", specification = "10"),
            ProductBean(id = 41, factoryNo = "18079", productName = "熟肚", specification = "10"),
            ProductBean(id = 68, factoryNo = "292", productName = "猪耳", specification = "10"),
            ProductBean(id = 179, factoryNo = "10.07957", productName = "猪耳", specification = "10"),
            ProductBean(id = 226, factoryNo = "10.01293", productName = "猪耳", specification = "10"),
            ProductBean(id = 99, factoryNo = "10.15289", productName = "猪耳", specification = "10")
    )

    private fun salesProduct(bean: SalesProduct? = null) {
        var specification = 0.0
        var salesProductBean = SalesProduct()
        var product: ProductBean? = null
        val view = inflater.inflate(R.layout.list_item_sales_statistics, recycler_view, false)
        if (bean != null) {
            salesProductBean = bean
            specification = getSpecification(bean.specification)
            view.tv_product.contentText = bean.factoryNo + bean.productName
            view.tv_weight.contentText = bean.salesWeight.toString()
            view.tv_number.contentText = bean.salesNumber.toString()
            view.tv_price.contentText = bean.salesPrice.toString()
            view.tv_total_price.contentText = bean.salesTotalPrice.toString()
            if (specification == 0.0) {
                view.tv_weight.keyListener = DigitsKeyListener.getInstance("0123456789")
            } else {
                view.tv_weight.keyListener = null
            }
        }
        view.tv_product.onSymbolClicked {
            /*  if (product == null) {
                  return@onRightSymbolClicked
              }
              messageDialog(msg = "是否删除“${product?.factoryNo}${product?.productName}”?") { _, _ ->
                  product = null
                  view.tv_product.contentText = ""
                  view.tv_number.contentText = ""
                  view.tv_weight.contentText = ""
                  view.tv_price.contentText = ""
                  view.tv_total_price.contentText = ""
              }*/
            activityForResult<ProductInfoListActivity>(
                    Constants.DATA to Constants.SELECTOR
            ) {
                product = it?.getSerializableExtra(Constants.DATA) as ProductBean?
                salesProductBean.productId = product?.id ?: 0
                salesProductBean.factoryNo = product?.factoryNo.orEmpty()
                salesProductBean.productName = product?.productName.orEmpty()
                view.tv_product.contentText = product?.factoryNo + product?.productName
                specification = getSpecification(product?.specification)
                if (specification == 0.0) {
                    view.tv_weight.keyListener = DigitsKeyListener.getInstance("0123456789")
                } else {
                    view.tv_weight.keyListener = null
                    salesProductBean.salesWeight = specification.mulEx(salesProductBean.salesNumber).toDouble()
                    view.tv_weight.contentText = salesProductBean.salesWeight.toString()
                }
            }
        }
        view.tv_product.onContentClicked {
            bottomSingleDialog(list = list.map { it.factoryNo + it.productName }) { _, s ->
                product = list.find { it.factoryNo + it.productName == s }
                if (product != null) {
                    salesProductBean.productId = product?.id ?: 0
                    salesProductBean.factoryNo = product?.factoryNo.orEmpty()
                    salesProductBean.productName = product?.productName.orEmpty()
                    view.tv_product.contentText = product?.factoryNo + product?.productName
                    specification = getSpecification(product?.specification)
                    if (specification == 0.0) {
                        view.tv_weight.keyListener = DigitsKeyListener.getInstance("0123456789")
                    } else {
                        view.tv_weight.keyListener = null
                        salesProductBean.salesWeight = specification.mulEx(salesProductBean.salesNumber).toDouble()
                        view.tv_weight.contentText = salesProductBean.salesWeight.toString()
                    }
                }
            }

        }

        view.tv_number.afterTextChangedListener { editable, _ ->
            salesProductBean.salesNumber = editable?.toString()?.toIntOrNull()
            view.tv_weight.contentText = specification.mulEx(salesProductBean.salesNumber).toString()
        }

        view.tv_weight.afterTextChangedListener { editable, _ ->
            salesProductBean.salesWeight = editable?.toString()?.toDoubleOrNull()

            val totalPrice = if (view.tv_weight.keyListener == null) { //定装
                salesProductBean.salesNumber?.mulEx(salesProductBean.salesPrice)
            } else {
                salesProductBean.salesWeight.mulEx(salesProductBean.salesPrice)
            }

            salesProductBean.salesTotalPrice = totalPrice?.toDouble()
            view.tv_total_price.contentText = totalPrice.toString()
        }
        view.tv_price.afterTextChangedListener { editable, _ ->
            salesProductBean.salesPrice = editable?.toString()?.toDoubleOrNull()
            val totalPrice = if (view.tv_weight.keyListener == null) { //定装
                salesProductBean.salesNumber?.mulEx(salesProductBean.salesPrice)
            } else {
                salesProductBean.salesWeight.mulEx(salesProductBean.salesPrice)
            }
            salesProductBean.salesTotalPrice = totalPrice?.toDouble()
            view.tv_total_price.contentText = totalPrice.toString()
        }
        recycler_view.addView(view)
        salesProductList.add(salesProductBean)
    }

    private fun getSpecification(str: String?): Double {
        val specification = str?.uppercase(Locale.getDefault())?.replace("KG", "")?.trim()
        return if (specification.isNumber())
            specification?.toDouble() ?: 0.0
        else
            0.0
    }
}